home *** CD-ROM | disk | FTP | other *** search
- Path: dawn.mmm.com!news
- From: kjhopps@mmm.com (Kevin J Hopps)
- Newsgroups: comp.lang.c++
- Subject: Re: Copy constructing an already default constructed object
- Date: 26 Jan 1996 13:29:59 GMT
- Organization: 3M - St. Paul, MN 55144-1000 US
- Message-ID: <4eal0n$hgq@dawn.mmm.com>
- References: <4e906b$stk@elaine32.Stanford.EDU>
- Reply-To: kjhopps@mmm.com
-
- brien oberstein (brien@leland.Stanford.EDU) wrote:
- > I'd like to get some opinions on the best/cleanest way
- > to accomplish the following:
-
- > I've got an object which has already been constructed
- > via its default constructor which just sets all pointers
- > to NULL. Whats the best way to deep-copy into it?
-
- [ example and discussion arriving at the conclusion that
- overloaded operator=() is required ]
-
- > //
- > // deep-copy =
- > //
- > A& A::operator =(const A& other)
- > {
- > A empty;
- > A tmp(other);
- > memcpy(this, &tmp, sizeof(A));
- > memcpy(&tmp, &empty, sizeof(A));
- > return *this;
- > }
-
-
- > I'd like to know what people think of the solution I've reached.
- > I figure that this type of shit is common enough so there should
- > be some widely accepted solution to this problem. Or maybe its
- > not, but believe me that the situation does occur.
-
- You have arrived at the correct conclusion -- that operator=() is
- what you are looking for. However, the function you've coded has
- some problems.
-
- First, you have to decide for yourself what the copy semantics of
- your class are -- deep or shallow. Regardless of what you decide,
- I think that the copy constructor and the assignment operator
- should produce identical results. Frequently one is written in
- terms of the other. Ultimately they must do an exhaustive copy
- of each data member. Using memcpy as above can overwrite
- compiler-generated data within the object and can have unpredictable
- results.
-
- Partial example:
-
- class A
- {
- public:
- A(const A& src);
- void operator=(const A& src);
- private:
- char* str;
- };
-
- A::A(const A& src)
- : str(0)
- {
- operator=(src);
- }
-
- void A::operator=(const A& rhs)
- {
- if (this != &rhs) {
- delete [] str;
- if (rhs.str == 0)
- str = 0;
- else {
- str = new char[strlen(rhs.str) + 1];
- strcpy(str, rhs.str);
- }
- }
- }
- --
- Kevin J. Hopps e-mail: kjhopps@mmm.com
- 3M Company phone: (612) 737-4643
- 3M Center, Bldg. 235-2D-57 fax: (612) 737-2700
- St. Paul, MN 55144-1000 Opinions are my own. I don't speak for 3M.
- But 3M speaks for me -- I did not write the following line:
-
- Opinions expressed herein are my own and may not represent those of 3M.
-